package com.cryann.mqttserver.config;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.TooLongFrameException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author cRyann
 * @date 2018/12/5 0005 10:13
 * @description:
 */
@Component
@Qualifier("nettyDecoder")
//@ChannelHandler.Sharable
public class NettyDecoder extends ByteToMessageDecoder {
    private static final int MAX_FRAME_SIZE = 1024;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int readableBytes = in.readableBytes();
        //不能让解码器缓冲大量的数据以致于耗尽可用的内存
        if ( readableBytes > MAX_FRAME_SIZE ) {
            //跳过所有的可读字节
            in.skipBytes(readableBytes);
            throw new TooLongFrameException("数据超过可缓存字节...");
        }
    }
}
